package com.teamsun.mqtt.entity.vo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 超过时间或者长度就移除
 * @author acer
 *
 */
public class DelayOCalQueue {

	DelayQueue<DelayWillRemoveMsg> delayQueue;
	
	int maxquesize=10000;
	
	int willremovesize=9500;
	
	static DelayOCalQueue delayOCalQueue=null;
	 
	private final  ReentrantLock lock = new ReentrantLock();
	
	/**
	 * 单例模式
	 * @return
	 */
	public static DelayOCalQueue getInstance(){
		if(delayOCalQueue==null)
			delayOCalQueue=new DelayOCalQueue();
		
		return delayOCalQueue;
	}
	
	private DelayOCalQueue(){
		delayQueue=new DelayQueue<>();
	}
	
	
	public  void  startClearThread(){
		
		
		new Thread(){
			
			public void  run(){
				
				while(true){
					try {
						DelayOCalQueue.this.take();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();;
	}
	/**
	 * 放进去
	 * @param delayWillRemoveMsg
	 * @return
	 */
	public  boolean  offer(DelayWillRemoveMsg delayWillRemoveMsg){
		
			lock.lock();
			if(delayQueue.size()>willremovesize){
			 delayQueue.remove(delayQueue.peek());
			}
			lock.unlock();
		return delayQueue.offer(delayWillRemoveMsg);
		
	}
	
	/**
	 * 取出来
	 * @return
	 * @throws InterruptedException
	 */
	public  Delayed   take() throws InterruptedException{
		
		lock.lock();
		if(delayQueue.size()>willremovesize){
			
			for (int i = 0; i < (maxquesize-willremovesize); 
					i++) {
				System.out.println("remove  because sizewillout");
				delayQueue.poll();
			}
		}
		lock.unlock();
		
		return delayQueue.take();
	}

	public DelayQueue<DelayWillRemoveMsg> getDelayQueue() {
		return delayQueue;
	}

	public void setDelayQueue(DelayQueue<DelayWillRemoveMsg> delayQueue) {
		this.delayQueue = delayQueue;
	}

	public int getMaxquesize() {
		return maxquesize;
	}

	public void setMaxquesize(int maxquesize) {
		this.maxquesize = maxquesize;
	}

	public int getWillremovesize() {
		return willremovesize;
	}

	public void setWillremovesize(int willremovesize) {
		this.willremovesize = willremovesize;
	}

	
	
}
